package com.oinux.playhelper.adapter;

import java.util.List;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.oinux.playhelper.R;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.util.TimeUtils;

public class AppStatusAdapter extends BaseAdapter {

	private Context context;
	private List<AppInfo> apps;
	private int runningColor;

	public AppStatusAdapter(Context context, List<AppInfo> apps, int runingColor) {
		this.context = context;
		this.apps = apps;
		this.runningColor = runingColor;
	}

	@Override
	public int getCount() {
		return apps.size();
	}

	@Override
	public AppInfo getItem(int position) {
		return apps.get(position);
	}

	@Override
	public long getItemId(int position) {
		return apps.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.app_status_item, null);
		}
		TextView appName = (TextView) convertView.findViewById(R.id.app_name);
		TextView appStatus = (TextView) convertView
				.findViewById(R.id.app_status);
		TextView appRunTime = (TextView) convertView
				.findViewById(R.id.app_run_time);
		ImageView appIcon = (ImageView) convertView.findViewById(R.id.app_icon);
		AppInfo appInfo = apps.get(position);
		if (appInfo.isRunning()) {
			appStatus.setText(R.string.running);
			appStatus.setTextColor(runningColor); 
			appRunTime.setVisibility(View.VISIBLE);
			appRunTime.setText(TimeUtils.formatTime(appInfo.getRunTime()));
			appRunTime.setTextColor(runningColor);
		} else {
			appStatus.setText(R.string.stoped);
			appStatus.setTextColor(context.getResources().getColor(
					R.color.stop_text));
			appRunTime.setVisibility(View.GONE);
		}
		appName.setText(appInfo.getName());
		Drawable icon = null;
		if (appInfo.getIcon() != null) {
			icon = appInfo.getIcon();
		} else {
			PackageManager packageManager = context.getPackageManager();
			try {
				icon = packageManager.getApplicationIcon(appInfo
						.getPackageName());
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}
		appIcon.setImageDrawable(icon);
		return convertView;
	}
}
